package com.dj.ms.support.transaction;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionChecker;
import com.aliyun.openservices.ons.api.transaction.TransactionProducer;
import com.dj.common.exception.BaseRunTimeException;
import com.dj.ms.configure.AliYunMQConfiguration;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Properties;

/**
 * <br>
 * <p></p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/10/21 下午1:26
 */
@Component
public class TransactionMsgHandler {
    Map<String, TransactionProducer> producerMap = Maps.newConcurrentMap();

    @Autowired
    private AliYunMQConfiguration aliYunMQConfiguration;

    public TransactionProducer loadProducer(String groupId, LocalTransactionChecker checker) {
        if (CollectionUtil.isNotEmpty(producerMap)
                && producerMap.containsKey(groupId)) {
            return producerMap.get(groupId);
        }
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.GROUP_ID, groupId);
        properties.put(PropertyKeyConst.AccessKey, aliYunMQConfiguration.getAccessKey());
        properties.put(PropertyKeyConst.SecretKey, aliYunMQConfiguration.getSecretKey());
        properties.put(PropertyKeyConst.NAMESRV_ADDR, aliYunMQConfiguration.getNamesrv_addr());
        properties.put(PropertyKeyConst.SuspendTimeMillis, "100");
        properties.put(PropertyKeyConst.CheckImmunityTimeInSeconds, 5);
        TransactionProducer producer = ONSFactory.createTransactionProducer(properties, checker);
        producer.start();
        producerMap.put(groupId, producer);

        if (ObjectUtil.isNull(producer)) {
            throw new BaseRunTimeException("获取事务消息Producer异常");
        }
        return producer;
    }

}
